package com.yaser.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import com.yaser.dao.UserDao;
import com.yaser.model.User;
import com.yaser.util.CustomHibernateDaoSupport;
import com.yaser.util.exceptions.FreeBoxDaoException;

@Repository("userDao")
public class UserDaoImpl extends CustomHibernateDaoSupport implements UserDao<User> {

	@SuppressWarnings("unchecked")
	@Override
	public User findUser(String name, String password) throws FreeBoxDaoException {

		// Criteria criteria =
		// getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(User.class);
		// criteria.add(Expression.eq("userName", name));
		// criteria.add(Expression.eq("password", password));
		// List<User> list = criteria.list();

		User user = null;
		try {
			List<User> list = getHibernateTemplate().find("from User u where u.userName = '" + name + "' and u.password = '" + password + "'");
			if (list.size() > 0)
				user = list.get(0);
		} catch (DataAccessException e) {
			throw new FreeBoxDaoException(e.getMessage());
		} catch (Exception e) {
			throw new FreeBoxDaoException(e.getMessage());
		}
		return user;
	}

	@Override
	public User save(User entity) {
		Serializable serializable = getHibernateTemplate().save(entity);
		entity.setId((Long) serializable);

		return entity;
	}

	@Override
	public void delete(User entity) {
		getHibernateTemplate().delete(entity);
	}

}
